/**
 * 系统管理  角色管理
 */
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="condition" class="user-search">
      <el-form-item label="搜索：">
        <el-select size="small" v-model="condition.status" placeholder="请选择">
          <el-option label="转态" value=""></el-option>
          <el-option label="正常" value="01"></el-option>
          <el-option label="已锁定" value="00"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="">
        <el-input
          size="small"
          v-model="condition.name"
          placeholder="输入角色名称"
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="search"
          >搜索</el-button
        >
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleEdit('add')"
          >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table
      size="small"
      :data="listData"
      highlight-current-row
      v-loading="loading"
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>

      <el-table-column sortable prop="name" label="角色名称" min-width="120">
      </el-table-column>

      <el-table-column sortable prop="code" label="角色代码" min-width="120">
      </el-table-column>

      <el-table-column
        sortable
        prop="createTime"
        label="生成时间"
        min-width="120"
      >
      </el-table-column>

      <el-table-column
        sortable
        prop="updateTime"
        label="修改时间"
        min-width="120"
      >
      </el-table-column>

      <el-table-column
        align="center"
        sortable
        prop="isLock"
        label="状态"
        min-width="50"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="01"
            inactive-value="00"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="setStatus(scope.row.id, scope.row.status)"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit('edit', scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="deleteUser(scope.$index, scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="success"
            @click="handleEdit('view', scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <Pagination
      v-bind:child-msg="pageparm"
      @callFather="callFather"
    ></Pagination>

    <!-- 编辑界面 -->
    <el-dialog
      :title="title"
      :visible.sync="editFormVisible"
      width="50%"
      @close="closeDialog('edit')"
    >
      <el-form
        label-width="100px"
        :model="editForm"
        ref="editForm"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="name">
              <el-input
                size="small"
                v-model="editForm.name"
                auto-complete="off"
                placeholder="请输入角色名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色代码" prop="code">
              <el-input
                size="small"
                v-model="editForm.code"
                auto-complete="off"
                placeholder="请输入角色代码"
              ></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input
                :rows="8"
                type="textarea"
                size="small"
                v-model="editForm.description"
                auto-complete="off"
                placeholder="请输入改角色描述内容"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="权限" prop="permissions">
              <el-cascader
                :options="perOptions"
                :props="props"
                v-model="perSelected"
                @change="initPerSelected"
                clearable
              >
              </el-cascader>
            </el-form-item>

            <el-form-item label="菜单" prop="menus">
              <el-cascader
                :options="menuOptions"
                :props="props"
                v-model="menuSelected"
                @change="initMenuSelected"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('edit')">取消</el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          class="title"
          @click="submitForm('editForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleDelete } from "../../api/userMG";
import Pagination from "../../components/Pagination";
import originData from "../../assets/data.json";
export default {
  inject: ["reload"],

  data() {
    //校验角色代码唯一
    var validateCode = async (rule, value, callback) => {
      let c = {
        id: this.editForm.id,
        code: value,
      };
      var d = await this.$axios.post("/role/checkCode", c);
      if (d.code == 200) {
        if (d.message == "0") {
          callback();
        } else {
          callback("角色代码已存在");
        }
      }
    };

    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      isView: false,
      menuAccessshow: false, //控制数据权限显示与隐藏
      title: "添加",
      props: { multiple: true, label: "name", value: "code" },
      perTypes: originData.types,

      permissions: [], //所有权限
      perOptions: [], //权限选项
      perSelected: [], //选中的权限

      fmenus: [], //所有父菜单
      smenus: [], //所有子菜单
      menuOptions: [], //菜单选项
      menuSelected: [], //选中的菜单

      editForm: {
        id: "",
        name: "",
        code: "",
        description: "",
        permissions: [],
        menus: [],
      },
      // rules 表单验证
      rules: {
        name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        code: [
          { required: true, message: "请输入角色代码", trigger: "blur" },
          { validator: validateCode, trigger: "blur" },
          {
            pattern: /^[A-Za-z0-9]{3,20}$/,
            required: true,
            message: "代码只包含大小写字母或数字,且长度为3-20",
            trigger: "blur",
          },
        ],
      },
      condition: {
        currentPage: 1,
        pageSize: 10,
        status: "",
        name: "",
      },
      listData: [], //角色数据
      // 选中
      checkmenu: [],
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  // 注册组件
  components: {
    Pagination,
  },
  /**
   * 创建完毕
   */
  created() {
    this.init();
    this.getActivePermissions();
    this.getMenus();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    // 获取角色列表
    async init() {
      var d = await this.$axios.post("/role/page", this.condition);
      if (d.code == 200) {
        this.listData = d.data.records;
        this.pageparm.currentPage = d.data.current;
        this.pageparm.pageSize = d.data.size;
        this.pageparm.total = d.data.total;
      }
    },

    /**
     * 权限相关
     */
    //获取所有正常状态的权限
    async getActivePermissions() {
      var d = await this.$axios.get("/permission/activeAll");
      if (d.code == 200) {
        this.permissions = d.data;
      }
      this.initPermission(this.perTypes, this.permissions);
    },
    //初始化权限下拉框选项
    initPermission(types, permissions) {
      let option = [];
      for (let i = 0; i < types.length; i++) {
        option.push({
          name: types[i].name,
          code: types[i].code,
          children: this.getPermissionsByType(types[i].code, permissions),
        });
      }
      this.perOptions = option;
    },
    //根据权限类型获取权限id
    getPermissionsByType(typeCode, permissions) {
      let option = [];
      for (let i = 0; i < permissions.length; i++) {
        if (permissions[i].type == typeCode) {
          option.push({
            name: permissions[i].name,
            code: permissions[i].id,
          });
        }
      }
      return option;
    },
    //处理选中之后的值给表单
    initPerSelected(val) {
      let ids = [];
      for (let i = 0; i < val.length; i++) {
        ids.push(val[i][1]);
      }
      this.editForm.permissions = ids;
    },
    //初始化已选中的权限
    setPerSelected(permissions) {
      let selected = [];
      for (let i = 0; i < permissions.length; i++) {
        selected.push([permissions[i].type, permissions[i].id]);
      }
      this.perSelected = selected;
      this.initPerSelected(selected);
    },

    /**
     * 菜单相关
     */
    //获取父子菜单
    async getMenus() {
      var d = await this.$axios.get("/menu/parentMenu");
      if (d.code == 200) {
        this.fmenus = d.data;
      }
      var a = await this.$axios.get("/menu/subMenu");
      if (a.code == 200) {
        this.smenus = a.data;
      }
      this.initMenus();
    },
    //初始化下拉框的内容
    initMenus() {
      let option = [];
      for (let i = 0; i < this.fmenus.length; i++) {
        option.push({
          code: this.fmenus[i].id,
          name: this.fmenus[i].name,
          children: this.getMenuByParentId(this.fmenus[i].id),
        });
      }
      this.menuOptions = option;
    },
    //根据id获取子级下拉框
    getMenuByParentId(id) {
      let s = [];
      for (let i = 0; i < this.smenus.length; i++) {
        if (this.smenus[i].parentId == id) {
          s.push({
            code: this.smenus[i].id,
            name: this.smenus[i].name,
          });
        }
      }
      return s;
    },
    //处理选中之后的值给表单
    initMenuSelected(val) {
      let ids = [];
      for (let i = 0; i < val.length; i++) {
        ids.push(val[i][1]);
      }

      this.editForm.menus = ids;
    },
    //初始化已选中的菜单
    setMenuSelected(menus) {
      let selected = [];
      for (let i = 0; i < menus.length; i++) {
        if (menus[i].parentId != "00") {
          selected.push([menus[i].parentId, menus[i].id]);
        }
      }
      this.menuSelected = selected;
      this.initMenuSelected(selected);
    },

    //修改用户状态
    async setStatus(id, status) {
      this.loading = true;
      let param = {
        id: id,
        status: status,
      };
      var d = await this.$axios.put("/role/status", param);
      if (d.code == 200) {
        this.$message.success(d.message);
      } else {
        this.$message.error(d.message);
      }
      this.loading = false;
    },
    // 分页插件事件
    callFather(parm) {
      this.condition.currentPage = parm.currentPage;
      this.condition.pageSize = parm.pageSize;
      this.init();
    },
    // 搜索事件
    search() {
      this.init();
    },
    //显示编辑界面
    handleEdit: function (name, row) {
      this.editFormVisible = true;
      if (row != undefined && row != "undefined") {
        this.isAdd = false;
        this.title = "修改";
        if (name == "view") {
          this.isView = true;
        } else {
          this.isView = false;
        }
        this.editForm.id = row.id;
        this.editForm.name = row.name;
        this.editForm.code = row.code;
        this.setPerSelected(row.permissions);
        this.setMenuSelected(row.menus);
        this.editForm.description = row.description;
      } else {
        this.title = "添加";
        this.isAdd = true;
        this.isView = false;
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(async (valid) => {
        if (valid) {
          if (this.isAdd) {
            var d = await this.$axios.post("/role/add", this.editForm);
            if (d.code == 200) {
              this.$message.success(d.message);
              this.editFormVisible = false;
              this.$refs.editForm.resetFields();
            } else {
              this.$message.error(d.message);
            }
          } else {
            var d = await this.$axios.put("/role/update", this.editForm);
            if (d.code == 200) {
              this.$message.success(d.message);
              this.editFormVisible = false;
            } else {
              this.$message.error(d.message);
            }
          }
          this.reload();
        } else {
          return false;
        }
      });
    },
    // 删除角色
    deleteUser(index, row) {
      this.$confirm("确定要删除吗?", "信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          roleDelete(row.roleId)
            .then((res) => {
              if (res.success) {
                this.$message({
                  type: "success",
                  message: "角色已删除！",
                });
                this.getdata(this.condition);
              } else {
                this.$message({
                  type: "info",
                  message: res.msg,
                });
              }
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error("角色删除失败，请稍后再试！");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == "edit") {
        this.editFormVisible = false;
        this.editForm = {
          id: "",
          name: "",
          code: "",
          description: "",
          permissions: [],
          menus: [],
        };
        this.perSelected = [];
        this.menuSelected = [];
        this.$refs.editForm.resetFields();
      } else if (dialog == "perm") {
        this.menuAccessshow = false;
        this.$refs.editForm.resetFields();
      }
    },
  },
};
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>

 